//
//  PhotoCell.swift
//  PhotoBrowser
//
//  Created by 游强辉 on 16/4/28.
//  Copyright © 2016年 youqianghui. All rights reserved.
//

import UIKit
import SDWebImage

class PhotoCell: UICollectionViewCell {
    
    //MARK:- 子控件
    lazy var imageView : UIImageView = UIImageView()
    
    //MARK:- 重写成员属性setter方法
    var picture : Picture? {
        didSet {
            //1.nil值校验
            guard let str = picture?.q_pic_url else {
                return
            }
            
            //2.获取小图
            var smallImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(str)
            
            if smallImage == nil {
                smallImage = UIImage(named: "empty_picture")
            }
            
            //3.计算ImageView的frame
            imageView.frame = setImageViewFrame(smallImage)
            
            //4.设置大图
            guard let bigStr = picture?.z_pic_url else {
                return
            }
            
            let bigUrl = NSURL(string: bigStr)
            
            imageView.sd_setImageWithURL(bigUrl, placeholderImage: smallImage, options: .RetryFailed) { (image, error, type, url) -> Void in
                
                self.imageView.frame = self.setImageViewFrame(image)
            }
            
        }
    }
    
    //MARK:- 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.addSubview(imageView)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK:- 设置ImageView的frame
extension PhotoCell {
    ///设置ImageView的frame
    func setImageViewFrame(image : UIImage) -> CGRect {
        let imageViewW = UIScreen.mainScreen().bounds.width
        let imageViewH = imageViewW / image.size.width * image.size.height
        let imageViewY = (UIScreen.mainScreen().bounds.height - imageViewH) * 0.5
        
        return CGRect(x: 0, y: imageViewY, width: imageViewW, height: imageViewH)
    }
}
